import { initParticlesJS } from '../particles.js'

// 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            //粒子效果
            initParticlesJS();

            // 检查用户登录状态并更新界面
            updateUserInterface();

            // 加载个人资料
            loadProfileData();

            // 加载浏览历史
            loadHistory();

            // 加载我的帖子
            loadMyPosts();

            // 加载我的收藏
            loadMyFavorites();

            // 设置编辑资料功能
            setupEditProfile();

            // 设置正在开发中的功能
            setupDevelopmentFeatures();

            // 移动菜单切换
            document.getElementById('mobile-menu-btn').addEventListener('click', function() {
                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu.classList.contains('hidden')) {
                    mobileMenu.classList.remove('hidden');
                } else {
                    mobileMenu.classList.add('hidden');
                }
            });

            // 更新购物车数量
            updateCartCount();
        });

        // 更新用户界面
        function updateUserInterface() {
            const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
            const authSection = document.getElementById('user-auth-section');
            const infoSection = document.getElementById('user-info-section');
            
            if (user) {
                authSection.classList.add('hidden');
                infoSection.classList.remove('hidden');
                document.getElementById('username').textContent = user.username;
                document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';

                // 退出登录
                document.getElementById('logout-btn').addEventListener('click', function() {
                    localStorage.removeItem('currentUser');
                    window.location.href = 'index.html';
                });
            } else {
                authSection.classList.remove('hidden');
                infoSection.classList.add('hidden');
                // 未登录用户访问个人中心，跳转到登录页
                window.location.href = 'auth.html';
            }
        }

        // 更新购物车数量
        function updateCartCount() {
            const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
            const cartCount = document.getElementById('cart-count');
            cartCount.textContent = cart.length;
        }

        // 加载个人资料
        function loadProfileData() {
            const user = JSON.parse(localStorage.getItem('currentUser'));
            if (!user) return;

            // 设置头像
            document.getElementById('profile-avatar-large').src = user.avatar || 'https://picsum.photos/150/150';
            
            // 设置用户名
            document.getElementById('profile-username').textContent = user.nickname;
            document.getElementById('edit-username').value = user.username;
            
            // 设置邮箱
            document.getElementById('profile-email').textContent = user.email || '未设置邮箱';
            document.getElementById('edit-email').value = user.email || '';
            
            // 设置注册日期
            document.getElementById('profile-register-date').textContent = 
                new Date(user.create_time || Date.now()).toLocaleDateString('zh-CN');
            
            // 设置个人简介
            document.getElementById('profile-bio').textContent = user.bio || '这个人很懒，还没有写个人简介...';
            document.getElementById('edit-bio').value = user.bio || '';
        }

        // 加载浏览历史
        function loadHistory() {
            const history = JSON.parse(localStorage.getItem('viewHistory') || '[]');
            const container = document.getElementById('history-items');
            
            if (history.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-8 text-gray-400 col-span-full">
                        <i class="fas fa-eye-slash text-3xl mb-2"></i>
                        <p>暂无浏览记录</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = '';
            
            // 只显示最近5条记录
            history.slice(0, 5).forEach(item => {
                const itemElement = document.createElement('div');
                itemElement.className = 'bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition';
                itemElement.innerHTML = `
                    <div class="flex items-center">
                        <img src="${item.image || 'https://picsum.photos/80/60'}" alt="${item.title}" class="w-16 h-12 object-cover rounded mr-3">
                        <div>
                            <h4 class="font-medium text-sm line-clamp-1">${item.title}</h4>
                            <p class="text-xs text-gray-500">${new Date(item.date).toLocaleDateString('zh-CN')}</p>
                        </div>
                    </div>
                `;
                itemElement.addEventListener('click', () => {
                    if (item.url) window.location.href = item.url;
                });
                container.appendChild(itemElement);
            });
        }

        // 加载我的帖子
        function loadMyPosts() {
            const user = JSON.parse(localStorage.getItem('currentUser'));
            if (!user) return;
            
            const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
            const myPosts = posts.filter(post => post.author === user.username);
            const container = document.getElementById('my-posts');
            
            if (myPosts.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-8 text-gray-400">
                        <i class="fas fa-comment-dots text-3xl mb-2"></i>
                        <p>暂无发布的帖子</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = '';
            
            // 只显示最近3条帖子
            myPosts.slice(0, 3).forEach(post => {
                const postElement = document.createElement('div');
                postElement.className = 'p-4 hover:bg-gray-50 transition';
                postElement.innerHTML = `
                    <div class="flex items-start">
                        <div class="flex-shrink-0 mr-4">
                            <div class="bg-blue-100 text-blue-600 w-10 h-10 rounded-full flex items-center justify-center">
                                <i class="fas fa-comment"></i>
                            </div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <h3 class="text-lg font-medium text-gray-900 mb-1">
                                <a href="post.html?id=${post.id}" class="hover:text-blue-600">${post.title}</a>
                            </h3>
                            <div class="flex flex-wrap items-center text-sm text-gray-500">
                                <span class="mr-3"><i class="fas fa-tag mr-1"></i>${post.section}</span>
                                <span class="mr-3"><i class="far fa-clock mr-1"></i>${new Date(post.date).toLocaleDateString('zh-CN')}</span>
                            </div>
                        </div>
                        <div class="ml-4 flex flex-col items-end">
                            <div class="flex space-x-4 text-sm text-gray-500">
                                <span><i class="far fa-thumbs-up mr-1"></i>${post.likes || 0}</span>
                                <span><i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0}</span>
                            </div>
                        </div>
                    </div>
                `;
                container.appendChild(postElement);
            });
        }

        // 加载我的收藏
        function loadMyFavorites() {
            const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
            const container = document.getElementById('my-favorites');
            
            if (favorites.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-8 text-gray-400 col-span-full">
                        <i class="far fa-star text-3xl mb-2"></i>
                        <p>暂无收藏内容</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = '';
            
            // 只显示最近4条收藏
            favorites.slice(0, 4).forEach(item => {
                const itemElement = document.createElement('div');
                itemElement.className = 'bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition';
                itemElement.innerHTML = `
                    <div class="flex items-center">
                        <img src="${item.image || 'https://picsum.photos/80/60'}" alt="${item.title}" class="w-16 h-12 object-cover rounded mr-3">
                        <div>
                            <h4 class="font-medium text-sm line-clamp-1">${item.title}</h4>
                            <p class="text-xs text-gray-500">${item.type || '收藏'}</p>
                        </div>
                    </div>
                `;
                itemElement.addEventListener('click', () => {
                    if (item.url) window.location.href = item.url;
                });
                container.appendChild(itemElement);
            });
        }

        // 设置编辑资料功能
        function setupEditProfile() {
            const editBtn = document.getElementById('edit-profile-btn');
            const editModal = document.getElementById('edit-profile-modal');
            const closeEditBtn = document.getElementById('close-edit-modal');
            const cancelEditBtn = document.getElementById('cancel-edit');
            const editForm = document.getElementById('edit-profile-form');
            
            if (!editBtn || !editModal || !closeEditBtn || !cancelEditBtn || !editForm) return;
            
            // 打开编辑模态框
            editBtn.addEventListener('click', function() {
                editModal.classList.remove('hidden');
            });
            
            // 关闭编辑模态框
            closeEditBtn.addEventListener('click', function() {
                editModal.classList.add('hidden');
            });
            
            // 取消编辑
            cancelEditBtn.addEventListener('click', function() {
                editModal.classList.add('hidden');
            });
            
            // 提交编辑表单
            editForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const user = JSON.parse(localStorage.getItem('currentUser'));
                if (!user) return;
                
                // 更新用户信息
                user.username = document.getElementById('edit-username').value;
                user.email = document.getElementById('edit-email').value;
                user.bio = document.getElementById('edit-bio').value;
                
                // 处理头像上传
                const avatarInput = document.getElementById('edit-avatar');
                if (avatarInput.files && avatarInput.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        user.avatar = e.target.result;
                        saveUserChanges(user);
                    };
                    reader.readAsDataURL(avatarInput.files[0]);
                } else {
                    saveUserChanges(user);
                }
            });
        }

        // 保存用户更改
        function saveUserChanges(user) {
            // 更新localStorage中的用户数据
            localStorage.setItem('currentUser', JSON.stringify(user));
            
            // 更新用户列表中的用户数据
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const userIndex = users.findIndex(u => u.id === user.id);
            if (userIndex !== -1) {
                users[userIndex] = user;
                localStorage.setItem('users', JSON.stringify(users));
            }
            
            // 重新加载个人资料
            loadProfileData();
            
            // 更新导航栏中的用户信息
            updateUserInterface();
            
            // 关闭编辑模态框
            document.getElementById('edit-profile-modal').classList.add('hidden');
            
            // 显示成功通知
            showNotification('个人资料更新成功');
        }

        // 设置正在开发中的功能
        function setupDevelopmentFeatures() {
            const devFeatureButtons = [
                document.getElementById('communityBtn'),
                document.getElementById('techniqueBtn')
            ];
            
            const devModal = document.getElementById('development-modal');
            const closeDevModal = document.getElementById('close-dev-modal');
            
            devFeatureButtons.forEach(button => {
                if (button) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault();
                        devModal.classList.remove('hidden');
                    });
                }
            });
            
            if (closeDevModal) {
                closeDevModal.addEventListener('click', function() {
                    devModal.classList.add('hidden');
                });
            }
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.createElement('div');
            notification.className = 'fixed bottom-4 right-4 bg-green-500 text-white p-4 rounded-lg shadow-lg z-50';
            notification.textContent = message;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('opacity-0', 'transition-opacity', 'duration-300');
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 2000);
        }